<template>
  <div class="page-wrapper">
    <div class="app-container">
      <!-- 页面头部 -->
      <PageHeader back-text="返回项目列表" back-type="back" :title="projectInfo.proName || '加载中...'" />

      <!-- 项目详情卡片 -->
      <ProjectDetail :project-info="projectInfo" :loading="projectLoading" />

      <!-- 回款信息列表卡片 -->
      <el-card class="box-card receive-money-card mb-6">
        <template #header>
          <div class="flex justify-between items-center">
            <div class="card-header-left">
              <span class="title">项目计划</span>
              <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                  <el-button type="info" plain icon="RefreshLeft" @click="handleRevertPlanAuditFlow"
                    v-hasPermi="['project:plan:audit']" :disabled="!canRevertPlanAuditFlow || isViewMode"
                    size="default">
                    重置审核流程
                  </el-button>
                </el-col>
              </el-row>
            </div>
            <div class="flex items-center" style="gap: 12px">
              <ProjectStatusDisplay label="项目计划审核状态" :status-options="approval_commit_status"
                :status-value="planAuditStatusValue" />
              <el-button type="primary" icon="Refresh" @click="loadReceiveMoneyNodes" :loading="receiveMoneyLoading"
                :disabled="isViewMode">刷新</el-button>
            </div>
          </div>
        </template>

        <!-- 回款信息列表 -->
        <div v-loading="receiveMoneyLoading" class="receive-money-list">
          <div v-if="receiveMoneyNodes.length === 0" class="empty-state">
            <el-empty description="暂无回款节点信息" />
          </div>

          <!-- 表头 -->
          <div v-if="receiveMoneyNodes.length > 0" class="list-header">
            <div class="header-cell header-order">节点序号</div>
            <div class="header-cell header-title left-align">付款节点</div>
            <div class="header-cell header-remark left-align">备注</div>
            <div class="header-cell header-status">计划状态</div>
            <div class="header-cell header-action">技术流程计划</div>
          </div>

          <!-- 回款节点项 -->
          <div v-for="(receiveNode, index) in receiveMoneyNodes" :key="receiveNode.id" class="receive-node-item">
            <!-- 回款节点主行 -->
            <div class="receive-node-row">
              <div class="node-cell node-order">
                <span>{{ receiveNode.receiveOrder || '-' }}</span>
              </div>
              <div class="node-cell node-title left-align">
                <el-tooltip :content="receiveNode.nodeTitle" placement="top" :disabled="!receiveNode.nodeTitle">
                  <span class="text-overflow">{{ receiveNode.nodeTitle }}</span>
                </el-tooltip>
              </div>
              <div class="node-cell node-remark left-align">
                <el-tooltip :content="receiveNode.remark" placement="top" :disabled="!receiveNode.remark">
                  <span class="text-overflow">{{ receiveNode.remark || '-' }}</span>
                </el-tooltip>
              </div>
              <div class="node-cell node-status">
                <dict-tag :options="node_split_status" :value="receiveNode.hasPlanNode" />
              </div>
              <div class="node-cell node-action expand-cell">
                <div class="expand-button" :class="{ 'expanded': receiveNode.expanded }"
                  @click="toggleExpand(receiveNode, index)">
                  <span class="expand-text">{{ receiveNode.expanded ? '收起' : '新增技术流程' }}</span>
                  <el-icon class="expand-arrow" :class="{ 'rotated': receiveNode.expanded }">
                    <ArrowDown />
                  </el-icon>
                </div>
              </div>
            </div>

            <!-- 展开的计划节点内容 -->
            <div v-show="receiveNode.expanded" class="expand-content">
              <div class="plan-header">
                <div class="plan-header-left">
                  <el-icon class="plan-icon">
                    <Document />
                  </el-icon>
                  <span class="plan-title">技术流程</span>
                  <el-tag size="small" type="info">{{ (receiveNode.planNodes || []).length }} 个计划</el-tag>
                </div>
                <div class="plan-header-actions">
                  <el-button type="primary" plain icon="Plus" @click="addInlinePlan(receiveNode)"
                    :disabled="isViewMode"> 新增技术流程
                  </el-button>
                </div>
              </div>

              <!-- 计划节点列表 -->
              <div class="plan-list" v-loading="receiveNode.planLoading">
                <el-table :data="receiveNode.planNodes" border style="width: 100%" size="small"
                  :header-cell-style="{ 'text-align': 'center' }" :row-class-name="planRowClassName">
                  <el-table-column label="流程序号" width="100" align="center">
                    <template #default="scope">
                      <template v-if="scope.row.isEditing">
                        <el-input-number v-model="scope.row.planOrder" :min="1" :max="999" controls-position="right"
                          style="width: 100px" />
                      </template>
                      <template v-else>
                        <div class="editable-cell" @dblclick="!isViewMode && editInlinePlan(scope.row)"
                          :title="isViewMode ? '' : '双击编辑'">
                          {{ scope.row.planOrder ?? '-' }}
                        </div>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column label="技术流程" align="left" :show-overflow-tooltip="true" width="1000">
                    <template #default="scope">
                      <template v-if="scope.row.isEditing">
                        <el-input v-model="scope.row.techFlow" placeholder="请输入技术流程（必填）"
                          :class="{ 'is-error': scope.row.techFlowError }"
                          @blur="scope.row.techFlowError = !scope.row.techFlow || scope.row.techFlow.trim() === ''" />
                      </template>
                      <template v-else>
                        <div class="editable-cell left" @dblclick="!isViewMode && editInlinePlan(scope.row)"
                          :title="isViewMode ? '' : '双击编辑'">
                          <span class="text-overflow">{{ scope.row.techFlow || '-' }}</span>
                        </div>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column label="备注" align="left" :show-overflow-tooltip="true" width="200">
                    <template #default="scope">
                      <template v-if="scope.row.isEditing">
                        <el-input v-model="scope.row.remark" placeholder="请输入备注" />
                      </template>
                      <template v-else>
                        <div class="editable-cell left" @dblclick="!isViewMode && editInlinePlan(scope.row)"
                          :title="isViewMode ? '' : '双击编辑'">
                          <span class="text-overflow">{{ scope.row.remark || '-' }}</span>
                        </div>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column label="流程状态" align="center" width="120">
                    <template #default="scope">
                      <dict-tag :options="node_split_status" :value="scope.row.hasFlowNode" />
                    </template>
                  </el-table-column>
                  <el-table-column label="工作内容计划" width="200" align="center">
                    <template #default="scope">
                      <template v-if="scope.row.isEditing">
                        <el-button type="primary" size="small"
                          @click="saveInlinePlan(receiveNode, scope.row)">保存</el-button>
                        <el-button size="small"
                          @click="cancelInlinePlan(receiveNode, scope.row, scope.$index)">取消</el-button>
                      </template>
                      <template v-else>
                        <div class="plan-op-buttons">
                          <el-tooltip content="编辑工作内容" placement="top">
                            <el-button link type="primary" size="small" @click="openFlowEditPage(scope.row)">
                              <el-icon>
                                <Operation />
                              </el-icon>
                            </el-button>
                          </el-tooltip>
                          <el-tooltip content="删除当前计划" placement="top">
                            <el-button link type="danger" size="small" @click="handleDeletePlan(receiveNode, scope.row)"
                              :disabled="isViewMode">
                              <el-icon>
                                <Delete />
                              </el-icon>
                            </el-button>
                          </el-tooltip>
                        </div>
                      </template>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 编辑流程信息对话框 -->
    <el-dialog v-model="flowDialogVisible" :title="`工作内容 - ${currentPlanTechFlow || ''}`" width="90%" top="5vh"
      :close-on-click-modal="false" @close="closeFlowDialog">
      <div>
        <!-- 新增流程按钮 -->
        <div class="flow-header">
          <div class="flow-header-left">
            <el-icon class="flow-icon">
              <Document />
            </el-icon>
            <span class="flow-title">计划工作内容</span>
            <el-tag size="small" type="info">{{ flowList.length }} 个工作内容</el-tag>
          </div>
          <div class="flow-header-actions">
            <el-button type="primary" plain icon="Plus" @click="addFlowRow" :disabled="isViewMode"> 新增工作内容 </el-button>
          </div>
        </div>

        <el-table :data="flowList" border style="width: 100%" size="small" :row-class-name="flowRowClassName"
          :header-cell-style="{ 'text-align': 'center' }" class="flow-table">
          <!-- 工作内容序号 -->
          <el-table-column label="内容序号" align="center" width="90" fixed="left">
            <template #default="scope">
              <el-input-number v-if="scope.row.isEditing" v-model="scope.row.flowOrder" :min="1" :max="999"
                :precision="0" size="small" controls-position="right" style="width: 100px" />
              <span v-else>{{ scope.row.flowOrder || '-' }}</span>
            </template>
          </el-table-column>

          <!-- 技术流程（统一使用每条流程对象的 techFlow） -->
          <el-table-column label="技术流程" align="left" width="300" fixed="left">
            <template #default="scope">
              <el-tooltip :content="scope.row.techFlow" placement="top" :disabled="!scope.row.techFlow">
                <span class="text-overflow tech-flow-display">{{ scope.row.techFlow || '-' }}</span>
              </el-tooltip>
            </template>
          </el-table-column>

          <!-- 工作内容：显示不完直接换行，无行数限制 -->
          <el-table-column label="工作内容" align="left" fixed="left" width="300">
            <template #default="scope">
              <el-input v-if="scope.row.isEditing" v-model="scope.row.workContent" type="textarea" :rows="3"
                placeholder="请输入工作内容" />
              <span v-else class="text-overflow no-clamp">{{ scope.row.workContent }}</span>
            </template>
          </el-table-column>

          <!-- 计划开始时间 -->
          <el-table-column width="140" label="计划开始时间" align="center">
            <template #default="scope">
              <el-date-picker v-if="scope.row.isEditing" v-model="scope.row.planStartTime" type="date"
                value-format="YYYY-MM-DD" placeholder="选择日期" style="width: 100%" />
              <span v-else>{{ scope.row.planStartTime || '-' }}</span>
            </template>
          </el-table-column>

          <!-- 计划结束时间 -->
          <el-table-column width="140" label="计划完成时间" align="center">
            <template #default="scope">
              <el-date-picker v-if="scope.row.isEditing" v-model="scope.row.planEndTime" type="date"
                value-format="YYYY-MM-DD" placeholder="选择日期" style="width: 100%" />
              <span v-else>{{ scope.row.planEndTime || '-' }}</span>
            </template>
          </el-table-column>

          <!-- 详细工作计划（列头保留提示，单元格仅溢出提示） -->
          <el-table-column label="详细工作计划" align="left" width="300" :show-overflow-tooltip="true">
            <template #header>
              <el-tooltip content="详细填写具体工作任务、完成时间节点、人员安排" placement="top">
                <span>详细工作计划</span>
              </el-tooltip>
            </template>
            <template #default="scope">
              <el-input v-if="scope.row.isEditing" v-model="scope.row.detailWorkPlan" type="textarea" :rows="3"
                placeholder="请输入该项工作内容对应的具体工作任务、完成时间节点、人员安排" />
              <span v-else class="text-overflow no-clamp">{{ scope.row.detailWorkPlan }}</span>
            </template>
          </el-table-column>

          <!-- 计划分项工作内容占比 -->
          <el-table-column width="130" label="该项工作内容占比（%）" align="center">
            <template #default="scope">
              <PercentageInput v-if="scope.row.isEditing" v-model="scope.row.planRatio"
                placeholder="请输入占比（0-100，保留两位小数）" :required="true"
                :class="{ 'is-error': !scope.row.planRatio || scope.row.planRatio <= 0 }"
                @change="triggerCalculation(scope.row)" />
              <span v-else>
                <span v-if="scope.row.planRatio">{{ formatPercentage(scope.row.planRatio) }}</span>
                <span v-else>-</span>
              </span>
            </template>
          </el-table-column>

          <!-- 人员 -->
          <el-table-column width="110" label="人员（人）" align="center">
            <template #default="scope">
              <PersonInput v-if="scope.row.isEditing" v-model="scope.row.staffAmount" :min="0"
                placeholder="请输入人数（大于0的整数）" :required="true"
                :class="{ 'is-error': !scope.row.staffAmount || scope.row.staffAmount <= 0 }"
                @change="triggerCalculation(scope.row)" />
              <span v-else>
                <span v-if="scope.row.staffAmount">{{ scope.row.staffAmount }}人</span>
                <span v-else>-</span>
              </span>
            </template>
          </el-table-column>

          <!-- 工天 -->
          <el-table-column width="120" label="工天（天）" align="center">
            <template #default="scope">
              <DayInput v-if="scope.row.isEditing" v-model="scope.row.workDays" placeholder="请输入工天（大于0，保留两位小数）"
                :required="true" :class="{ 'is-error': !scope.row.workDays || scope.row.workDays <= 0 }"
                @change="triggerCalculation(scope.row)" />
              <span v-else>
                <span v-if="scope.row.workDays">{{ scope.row.workDays }}天</span>
                <span v-else>-</span>
              </span>
            </template>
          </el-table-column>

          <!-- 计划总人工天（改为手动填写） -->
          <el-table-column width="120" label="计划总人工天（天）" align="center">
            <template #default="scope">
              <DayInput v-if="scope.row.isEditing" v-model="scope.row.totalStaffDays" placeholder="请输入总人工天（大于0，保留两位小数）"
                :required="true" :class="{ 'is-error': !scope.row.totalStaffDays || scope.row.totalStaffDays <= 0 }"
                @change="triggerCalculation(scope.row)" />
              <span v-else>
                <span v-if="scope.row.totalStaffDays">{{ scope.row.totalStaffDays }}天</span>
                <span v-else>-</span>
              </span>
            </template>
          </el-table-column>

          <!-- 单位绩效 -->
          <el-table-column v-if="hasPerformancePermission" width="150" label="单位绩效（元/人/天）" align="center">
            <template #default="scope">
              <MoneyInput v-if="scope.row.isEditing" v-model="scope.row.unitPerf" placeholder="请输入单位绩效（保留两位小数）"
                :required="false" :min="0" @change="triggerCalculation(scope.row)" />
              <span v-else>
                <span v-if="scope.row.unitPerf">{{ formatAmount(scope.row.unitPerf) }}元</span>
                <span v-else>-</span>
              </span>
            </template>
          </el-table-column>

          <!-- 该项工作内容绩效（元） -->
          <el-table-column v-if="hasPerformancePermission" width="150" label="该项工作内容绩效（元）" align="center">
            <template #default="scope">
              <span class="calculated-value">{{ formatAmount(scope.row.planPerf) || 0 }}元</span>
            </template>
          </el-table-column>

          <!-- 差旅 -->
          <el-table-column v-if="hasPerformancePermission" width="150" label="差旅（元）" align="center">
            <template #default="scope">
              <MoneyInput v-if="scope.row.isEditing" v-model="scope.row.travelCost" placeholder="请输入差旅费（保留两位小数）"
                :min="0" @change="calculateTotalPerf(scope.row)" />
              <span v-else>
                <span v-if="scope.row.travelCost">{{ formatAmount(scope.row.travelCost) }}元</span>
                <span v-else>-</span>
              </span>
            </template>
          </el-table-column>

          <!-- 办公费 -->
          <el-table-column v-if="hasPerformancePermission" width="150" label="办公费（元）" align="center">
            <template #default="scope">
              <MoneyInput v-if="scope.row.isEditing" v-model="scope.row.officeCost" placeholder="请输入办公费（保留两位小数）"
                :min="0" @change="calculateTotalPerf(scope.row)" />
              <span v-else>
                <span v-if="scope.row.officeCost">{{ formatAmount(scope.row.officeCost) }}元</span>
                <span v-else>-</span>
              </span>
            </template>
          </el-table-column>

          <!-- A1费用 -->
          <el-table-column v-if="hasPerformancePermission" width="150" label="A1费用（元）" align="center">
            <template #default="scope">
              <MoneyInput v-if="scope.row.isEditing" v-model="scope.row.a1Cost" placeholder="请输入A1费用（保留两位小数）" :min="0"
                @change="calculateTotalPerf(scope.row)" />
              <span v-else>
                <span v-if="scope.row.a1Cost">{{ formatAmount(scope.row.a1Cost) }}元</span>
                <span v-else>-</span>
              </span>
            </template>
          </el-table-column>

          <!-- A2费用 -->
          <el-table-column v-if="hasPerformancePermission" width="150" label="A2费用（元）" align="center">
            <template #default="scope">
              <MoneyInput v-if="scope.row.isEditing" v-model="scope.row.a2Cost" placeholder="请输入A2费用（保留两位小数）" :min="0"
                @change="calculateTotalPerf(scope.row)" />
              <span v-else>
                <span v-if="scope.row.a2Cost">{{ formatAmount(scope.row.a2Cost) }}元</span>
                <span v-else>-</span>
              </span>
            </template>
          </el-table-column>

          <!-- 总绩效（含成本） -->
          <el-table-column v-if="hasPerformancePermission" width="150" label="总绩效（含成本）（元）" align="center">
            <template #default="scope">
              <span class="calculated-value">{{ formatAmount(scope.row.totalPerf) || 0 }}元</span>
            </template>
          </el-table-column>

          <!-- 成本说明 -->
          <el-table-column width="200" label="成本说明" align="left">
            <template #default="scope">
              <el-input v-if="scope.row.isEditing" v-model="scope.row.costDescription" type="textarea" :rows="3"
                placeholder="请输入成本说明（可选）" />
              <el-tooltip v-else :content="scope.row.costDescription" placement="top"
                :disabled="!scope.row.costDescription">
                <span class="text-overflow">{{ scope.row.costDescription || '-' }}</span>
              </el-tooltip>
            </template>
          </el-table-column>

          <!-- 备注 -->
          <el-table-column label="备注" align="left" width="100">
            <template #default="scope">
              <el-input v-if="scope.row.isEditing" v-model="scope.row.remark" type="textarea" :rows="3"
                placeholder="请输入备注（可选）" />
              <el-tooltip v-else :content="scope.row.remark" placement="top" :disabled="!scope.row.remark">
                <span class="text-overflow">{{ scope.row.remark || '-' }}</span>
              </el-tooltip>
            </template>
          </el-table-column>

          <!-- 操作 -->
          <el-table-column label="操作" width="160" align="center" fixed="right">
            <template #default="scope">
              <template v-if="scope.row.isEditing">
                <el-button size="small" @click="cancelFlowRow(scope.row)">取消</el-button>
              </template>
              <template v-else>
                <el-tooltip content="编辑" placement="top">
                  <el-button link type="primary" size="small" @click="editFlowRow(scope.row)"
                    :disabled="isViewMode"><el-icon>
                      <Edit />
                    </el-icon></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button link type="danger" size="small" @click="deleteFlowRow(scope.row)"
                    :disabled="isViewMode"><el-icon>
                      <Delete />
                    </el-icon></el-button>
                </el-tooltip>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer" style="display: flex; justify-content: flex-end; gap: 8px;">
          <el-button type="success" icon="Check" :disabled="!hasEditingFlowData || isViewMode"
            @click="handleBatchSaveFlow">批量保存</el-button>
          <el-button @click="closeFlowDialog">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核流程组件 -->
    <ApprovalFlow v-model:visible="approvalFlowVisible" :business-type="businessType"
      :business-id="currentProjectForApproval?.id" :title="`项目计划审核-${projectInfo.proName || ''}`"
      @confirm="handleApprovalConfirm" @cancel="handleApprovalCancel" />

    <!-- 右下角固定提交审核按钮 -->
    <div class="fixed-submit-button" v-if="!isViewMode">
      <el-button type="primary" @click="handleSubmitPlan" v-hasPermi="['project:plan:audit']" size="large"
        class="submit-audit-btn" :loading="false">
        <el-icon>
          <Upload />
        </el-icon>
        <span>提交项目计划审核</span>
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getProDetail, revertPlanAuditFlow } from '@/api/project/init/proInfo';
import type { ProInfoVO } from '@/api/project/init/proInfo/types';
import { getReceiveMoneyNodesByProId } from '@/api/project/receive/index';
import { listProPlan, addProPlan, updateProPlan, delProPlan } from '@/api/project/plan/index';
import type { ProPlanForm } from '@/api/project/plan/types';
import { listProFlow, delProFlow, batchSaveProFlow } from '@/api/project/plan/flow';
import ProjectDetail from '@/views/project/components/ProjectDetail.vue';
import PageHeader from '@/views/project/components/PageHeader/index.vue';
import ProjectStatusDisplay from '@/views/project/components/ProjectStatusDisplay.vue';
import PercentageInput from '@/components/PercentageInput/index.vue';
import PersonInput from '@/components/PersonInput/index.vue';
import DayInput from '@/components/DayInput/index.vue';
import MoneyInput from '@/components/MoneyInput/index.vue';
import ApprovalFlow from '@/components/ApprovalFlow/index.vue';
import { formatAmount } from '@/components/NumberInput';
import { checkPermi } from '@/utils/permission';

const route = useRoute();
const router = useRouter();

// 页面渲染逻辑
const isViewMode = computed(() => router.options.history.state?.mode === 'view')

// 计算是否可以重置审核流程
const canRevertPlanAuditFlow = computed(() => {
  // 只有项目计划已提交、审核中、审核通过、审核不过时才允许重置
  return projectInfo.value && ['1', '2', '3', '4'].includes(planAuditStatusValue.value);
});

// 检查是否有绩效权限
const hasPerformancePermission = computed(() => {
  return checkPermi(['project:performance:query']);
});

// 获取字典数据
const { proxy } = getCurrentInstance();
const { node_split_status, approval_commit_status } = toRefs<any>(proxy?.useDict('node_split_status', 'approval_commit_status'));

// 项目信息
const projectInfo = ref<Partial<ProInfoVO>>({});
const projectLoading = ref(false);
// 兼容TS：从projectInfo中安全读取planAuditStatus（字符串或数字），默认'0'
const planAuditStatusValue = computed(() => {
  const anyInfo = projectInfo.value as any;
  return (anyInfo && (anyInfo.planAuditStatus ?? anyInfo.planAuditstatus ?? anyInfo.plan_audit_status)) ?? '0';
});

// 回款节点相关
const receiveMoneyNodes = ref([]);
const receiveMoneyLoading = ref(false);



/**
 * 获取项目信息
 * 根据路由参数中的项目ID获取详细信息
 */
const getProjectDetail = async () => {
  const proId = route.params.proId as string;
  if (!proId) {
    ElMessage.error('项目ID不能为空');
    return;
  }

  try {
    projectLoading.value = true;
    const res = await getProDetail(proId);
    projectInfo.value = res.data || {};
  } catch (error) {
    console.error('获取项目信息失败:', error);
    ElMessage.error('获取项目信息失败');
  } finally {
    projectLoading.value = false;
  }
};

/**
 * 加载回款节点列表
 */
const loadReceiveMoneyNodes = async () => {
  const proId = route.params.proId as string;
  if (!proId) {
    ElMessage.error('项目ID不能为空');
    return;
  }

  try {
    receiveMoneyLoading.value = true;
    const res = await getReceiveMoneyNodesByProId(proId);
    const nodes = res.data || [];

    // 为每个节点添加展开状态和计划节点数据
    receiveMoneyNodes.value = nodes.map((node: any) => ({
      ...node,
      expanded: false,
      planNodes: [],
      planLoading: false
    }));
  } catch (error) {
    console.error('获取回款节点失败:', error);
    ElMessage.error('获取回款节点失败');
  } finally {
    receiveMoneyLoading.value = false;
  }
};



/**
 * 加载计划节点列表
 */
const loadPlanNodes = async (receiveNode: any) => {
  try {
    // 保存当前未保存的编辑项
    const unsaved = saveUnsavedEditingPlans(receiveNode);
    receiveNode.planLoading = true;
    // 发送普通列表请求，只传receiveId
    const res = await listProPlan({
      receiveId: receiveNode.id
    });
    receiveNode.planNodes = wrapPlanNodes(res.data || []);
    // 恢复未保存的编辑项
    restoreUnsavedEditingPlans(receiveNode, unsaved);
  } catch (error) {
    console.error('获取计划节点失败:', error);
    ElMessage.error('获取计划节点失败');
  } finally {
    receiveNode.planLoading = false;
  }
};

/**
 * 切换展开状态
 */
const toggleExpand = (row: any, index: number) => {
  if (row.expanded) {
    // 收起
    row.expanded = false;
  } else {
    // 展开
    row.expanded = true;
    loadPlanNodes(row);
  }
};

/**
 * 删除计划节点
 */
const handleDeletePlan = async (receiveNode: any, planNode: any) => {
  try {
    await ElMessageBox.confirm(`确定删除计划序号 ${planNode.planOrder} 的计划节点吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await delProPlan(planNode.id);
    ElMessage.success('删除成功');

    // 刷新计划节点列表
    loadPlanNodes(receiveNode);
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除计划节点失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

/**
 * 新增计划节点 (行内)
 */
const addInlinePlan = (receiveNode: any) => {
  const newItem = {
    id: undefined,
    proId: receiveNode.proId,
    receiveId: receiveNode.id,
    techFlow: '',
    remark: '',
    planOrder: (receiveNode.planNodes?.length || 0) + 1,
    hasFlowNode: receiveNode.hasFlowNode || '',
    isEditing: true,
    saving: false,
    techFlowError: false,
    originalData: null
  } as any;
  if (!Array.isArray(receiveNode.planNodes)) receiveNode.planNodes = [];
  receiveNode.planNodes.push(newItem);
};

/**
 * 编辑行内计划节点
 */
const editInlinePlan = (row: any) => {
  row.originalData = JSON.parse(JSON.stringify(row));
  row.isEditing = true;
};

/**
 * 保存行内计划节点
 */
const saveInlinePlan = async (receiveNode: any, row: any) => {
  try {
    if (!row.planOrder || !row.techFlow || row.techFlow.trim() === '') {
      row.techFlowError = !row.techFlow || row.techFlow.trim() === '';
      ElMessage.warning('请完善计划序号与技术流程');
      return;
    }
    row.saving = true;
    const payload: ProPlanForm = {
      id: row.id,
      proId: row.proId ?? receiveNode.proId,
      receiveId: row.receiveId ?? receiveNode.id,
      techFlow: row.techFlow,
      remark: row.remark,
      planOrder: row.planOrder
    };
    if (payload.id) {
      await updateProPlan(payload);
      ElMessage.success('保存成功');
    } else {
      await addProPlan(payload);
      ElMessage.success('新增成功');
    }
    // 本行保存后应退出编辑态（绕过恢复逻辑）
    row.isEditing = false;
    row.originalData = null;
    // 刷新列表（其余未保存的编辑态将被恢复，当前保存行不会恢复为编辑态）
    await loadPlanNodes(receiveNode);
  } catch (e) {
    ElMessage.error('保存失败');
  } finally {
    row.saving = false;
  }
};

/**
 * 取消行内计划节点编辑
 */
const cancelInlinePlan = (receiveNode: any, row: any, index: number) => {
  if (row.id) {
    if (row.originalData) {
      const copy = { ...row.originalData };
      delete row.originalData;
      Object.assign(row, copy);
    }
    row.isEditing = false;
  } else {
    // 新增项取消则移除
    receiveNode.planNodes.splice(index, 1);
  }
};

// 保存未保存的编辑中的计划节点（排除正在保存saving中的行）
const saveUnsavedEditingPlans = (receiveNode: any) => {
  if (!receiveNode?.planNodes) return [] as any[];
  return receiveNode.planNodes
    .filter((n: any) => n.isEditing && !n.saving)
    .map((n: any) => ({
      ...n,
      originalData: n.originalData ? JSON.parse(JSON.stringify(n.originalData)) : null
    }));
};

// 恢复未保存的编辑中的计划节点（跳过正在保存的行）
const restoreUnsavedEditingPlans = (receiveNode: any, unsaved: any[]) => {
  if (!receiveNode?.planNodes || !unsaved?.length) return;
  unsaved.forEach((u) => {
    if (!u.id) {
      // 新增行：若不存在相同新增项，则追加到列表底部
      const exists = receiveNode.planNodes.find((x: any) => !x.id && x.planOrder === u.planOrder && x.techFlow === u.techFlow && x.isEditing);
      if (!exists) receiveNode.planNodes.push(u);
    } else {
      // 已有行：定位并替换为编辑态
      const idx = receiveNode.planNodes.findIndex((x: any) => x.id === u.id);
      if (idx > -1 && !receiveNode.planNodes[idx].saving) {
        receiveNode.planNodes[idx] = u;
      }
    }
  });
};

// 包装加载结果，附加isEditing/originalData
const wrapPlanNodes = (list: any[]) => list.map((it) => ({ ...it, isEditing: false, originalData: null }));

// 打开流程编辑页面
const openFlowEditPage = async (planRow: any) => {
  try {
    // 打开弹窗并加载该计划下的流程数据
    flowDialogVisible.value = true;
    currentPlanTechFlow.value = planRow.techFlow; // 兼容保留，但显示改为按行的 techFlow
    currentPlanNode.value = planRow; // 保存当前计划节点的完整信息
    await loadFlowList({ planId: planRow.id });
  } catch (e) {
    ElMessage.error('打开流程编辑失败');
  }
};

// 流程信息相关
const flowDialogVisible = ref(false);
const flowList = ref<any[]>([]);
const currentPlanTechFlow = ref(''); // 新增：用于保存当前计划节点的技术流程
const currentPlanNode = ref<any>(null); // 新增：用于保存当前计划节点的完整信息

// 审核流程相关
const approvalFlowVisible = ref(false);
const currentProjectForApproval = ref<any>(null);
const businessType = ref('PROJECT-SPLIT-PLAN');

const flowRowClassName = ({ row }: { row: any }) => (row.isEditing ? 'editing-row' : '');

const planRowClassName = ({ row }: { row: any }) => (row.isEditing ? 'editing-row' : '');

const loadFlowList = async (query: { planId?: string | number; proId?: string | number; receiveId?: string | number }) => {
  try {
    const res = await listProFlow(query as any);
    // list接口返回的是AxiosResponse，需要访问res.data获取流程数组
    flowList.value = (res.data || []).map((it: any) => ({ ...it, isEditing: false, originalData: null }));
  } catch (e) {
    console.error('获取流程列表失败', e);
    ElMessage.error('获取流程列表失败');
  }
};

const editFlowRow = (row: any) => {
  row.originalData = JSON.parse(JSON.stringify(row));
  row.isEditing = true;
};

const cancelFlowRow = (row: any) => {
  if (row.id) {
    // 编辑现有行
    if (row.originalData) {
      Object.assign(row, row.originalData);
      row.isEditing = false;
      row.originalData = null;
    }
  } else {
    // 新增行，直接移除
    const index = flowList.value.findIndex((item) => item === row);
    if (index > -1) {
      flowList.value.splice(index, 1);
    }
  }
};

// 单行删除：有 id 走后端批量删除接口（单条ID集合），无 id 直接前端移除
const deleteFlowRow = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定删除该流程吗？', '提示', { type: 'warning' });
    if (row.id) {
      await delProFlow([row.id]);
      ElMessage.success('删除成功');
      if (currentPlanNode.value?.id) {
        await loadFlowList({ planId: currentPlanNode.value.id });
      }
    } else {
      const index = flowList.value.findIndex((item) => item === row);
      if (index > -1) flowList.value.splice(index, 1);
      ElMessage.success('删除成功');
    }
  } catch (e) {
    if (e !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 格式化百分比（兼容字符串/空值）
const formatPercentage = (value: number | string) => {
  if (value === null || value === undefined || value === '') return '';
  const num = typeof value === 'number' ? value : Number(value);
  if (Number.isNaN(num)) return '';
  return `${num.toFixed(2)}%`;
};

// 触发计算
const triggerCalculation = (row: any) => {
  // 计算计划分项内容绩效 = 计划总人工天 × 单位绩效
  if (row.totalStaffDays && row.unitPerf) {
    row.planPerf = Number(row.totalStaffDays) * Number(row.unitPerf);
  } else {
    row.planPerf = 0;
  }

  // 计算总绩效
  calculateTotalPerf(row);
};

// 计算总绩效
const calculateTotalPerf = (row: any) => {
  let total = 0;

  // 基础绩效
  if (row.planPerf) {
    total += Number(row.planPerf);
  }

  // 成本费用
  if (row.travelCost) total += Number(row.travelCost);
  if (row.officeCost) total += Number(row.officeCost);
  if (row.a1Cost) total += Number(row.a1Cost);
  if (row.a2Cost) total += Number(row.a2Cost);

  row.totalPerf = total;
};

const addFlowRow = () => {
  const newRow = {
    id: undefined,
    proId: currentPlanNode.value?.proId,
    planId: currentPlanNode.value?.id,
    receiveId: currentPlanNode.value?.receiveId,
    flowOrder: flowList.value.length + 1,
    techFlow: currentPlanTechFlow.value || currentPlanNode.value?.techFlow || '',
    workContent: '',
    detailWorkPlan: '',
    planRatio: null,
    staffAmount: null,
    workDays: null,
    totalStaffDays: null,
    unitPerf: null,
    planPerf: null,
    travelCost: null,
    officeCost: null,
    a1Cost: null,
    a2Cost: null,
    totalPerf: null,
    costDescription: '',
    planStartTime: null,
    planEndTime: null,
    remark: '',
    isEditing: true,
    saving: false,
    originalData: null
  };
  flowList.value.push(newRow);
};

// 关闭流程编辑对话框
const closeFlowDialog = () => {
  // 清理所有正在编辑的行状态
  flowList.value.forEach((row) => {
    if (row.isEditing) {
      row.isEditing = false;
      row.originalData = null;
    }
  });

  flowDialogVisible.value = false;
  // 清理状态
  flowList.value = [];
  currentPlanTechFlow.value = '';
  currentPlanNode.value = null;
};

// 是否存在编辑中的流程数据（未保存态即 isEditing=true 或无 id）
const hasEditingFlowData = computed(() => flowList.value.some((item: any) => item.isEditing === true || !item.id));



/**
 * 批量保存流程
 */
const handleBatchSaveFlow = async () => {
  if (!hasEditingFlowData.value) {
    ElMessage.warning('没有处于编辑状态的数据可以保存');
    return;
  }

  try {
    // 直接选取未保存/编辑中的行
    const selectedRows = flowList.value.filter((row: any) => row.isEditing === true || !row.id);

    // 批量校验所有选中的行
    const validationErrors: string[] = [];
    selectedRows.forEach((row: any, index: number) => {
      const requiredFields = [];

      if (!row.planRatio || row.planRatio <= 0) {
        requiredFields.push('计划分项工作内容占比');
      }

      if (!row.staffAmount || row.staffAmount <= 0) {
        requiredFields.push('人员');
      }

      if (!row.workDays || row.workDays <= 0) {
        requiredFields.push('工天');
      }

      // 单位绩效已设置为不必填，移除验证

      if (requiredFields.length > 0) {
        validationErrors.push(`第${index + 1}行：${requiredFields.join('、')}`);
      }
    });

    if (validationErrors.length > 0) {
      ElMessage.error('有必填属性未填写，保存失败');
      return;
    }

    const submitData = selectedRows.map((row: any) => {
      const data = { ...row } as any;
      // 清理前端特有的属性，这些属性不应该发送到后端
      delete (data as any).isEditing;
      delete (data as any).originalData;
      delete (data as any).saving;

      // 修改流程信息时，将createBy和createTime设置为空
      data.createBy = null;
      data.createTime = null;

      // updateBy, updateTime 会由后端的FieldFill自动填充
      delete data.updateBy;
      delete data.updateTime;

      // 确保携带 techFlow 字段
      data.techFlow = row.techFlow;

      return data;
    });

    await batchSaveProFlow(submitData);
    ElMessage.success('批量保存成功');

    // 重新获取数据
    if (currentPlanNode.value) {
      await loadFlowList({ planId: currentPlanNode.value.id });
    }
  } catch (error) {
    ElMessage.error('批量保存失败');
  }
};

/**
 * 提交项目计划审核
 */
const handleSubmitPlan = () => {
  const proId = route.params.proId as string;
  if (!proId) {
    ElMessage.error('项目ID不能为空');
    return;
  }

  currentProjectForApproval.value = {
    id: proId,
    proName: projectInfo.value.proName || '项目计划'
  };
  approvalFlowVisible.value = true;
};

/**
 * 审核流程确认回调
 */
const handleApprovalConfirm = async () => {
  try {
    ElMessage.success('审核流程提交成功');
    approvalFlowVisible.value = false;
    currentProjectForApproval.value = null;
    // 刷新项目信息
    await getProjectDetail();
  } catch (error) {
    console.error('审核流程提交失败:', error);
    ElMessage.error('审核流程提交失败');
  }
};

/**
 * 审核流程取消回调
 */
const handleApprovalCancel = () => {
  approvalFlowVisible.value = false;
  currentProjectForApproval.value = null;
};

/**
 * 重置项目计划审核流程
 */
const handleRevertPlanAuditFlow = async () => {
  const proId = route.params.proId as string;
  if (!proId) {
    ElMessage.error('项目ID不能为空');
    return;
  }
  try {
    await ElMessageBox.confirm('确定要重置该项目计划的审核流程吗？重置后将回到未提交状态。', '确认重置', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await revertPlanAuditFlow(proId);
    ElMessage.success('重置审核流程成功');
    await getProjectDetail();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置审核流程失败:', error);
      ElMessage.error('重置审核流程失败');
    }
  }
};

onMounted(() => {
  getProjectDetail();
  loadReceiveMoneyNodes();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

/* 回款信息卡片样式 */
.receive-money-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 12px;
}

.card-header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.card-header-left .title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

/* 回款信息列表样式 */
.receive-money-list {
  width: 100%;
  overflow-x: auto;
  min-width: 1330px;
  /* 重新计算最小宽度：120 + 620 + 320 + 150 + 150 = 1360px */
}

.empty-state {
  padding: 40px 0;
}

/* 列表表头样式 */
.list-header {
  display: flex;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border: 1px solid #e4e7ed;
  border-radius: 8px 8px 0 0;
  padding: 12px 0;
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.header-cell {
  padding: 0 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-right: 1px solid #e4e7ed;
  text-align: center;
}

/* 表头列宽样式 - 使用最小宽度而不是绝对固定 */
.header-order {
  flex: 1 0 100px;
  min-width: 100px;
}

.header-title {
  flex: 2 0 620px;
  min-width: 620px;
}

.header-remark {
  flex: 1 0 320px;
  min-width: 320px;
}

.header-status {
  flex: 1 0 150px;
  min-width: 150px;
}

.header-action {
  flex: 1 0 150px;
  min-width: 150px;
}

/* 左对齐辅助类（表头与单元格） */
.header-cell.left-align {
  justify-content: flex-start;
  text-align: left;
}

.header-cell:last-child {
  border-right: none;
}

/* 回款节点项样式 */
.receive-node-item {
  border: 1px solid #e4e7ed;
  border-top: none;
}

.receive-node-item:last-child {
  border-radius: 0 0 8px 8px;
}

.receive-node-row {
  display: flex;
  background-color: #ffffff;
  transition: all 0.2s ease;
  cursor: pointer;
  min-height: 60px;
}

.receive-node-row:hover {
  background-color: #f5f7fa;
}

.node-cell {
  padding: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-right: 1px solid #f0f0f0;
  font-size: 14px;
  text-align: center;
}

.node-cell.left-align {
  justify-content: flex-start;
  text-align: left;
}

.node-cell:last-child {
  border-right: none;
}

/* 节点单元格列宽样式 - 使用最小宽度而不是绝对固定 */
.node-order {
  flex: 1 0 100px;
  min-width: 100px;
}

.node-title {
  flex: 2 0 620px;
  min-width: 620px;
}

.node-remark {
  flex: 1 0 320px;
  min-width: 320px;
}

.node-status {
  flex: 1 0 150px;
  min-width: 150px;
}

.node-action {
  flex: 1 0 150px;
  min-width: 150px;
}

.expand-cell {
  justify-content: center;
  cursor: pointer;
  display: flex;
  align-items: center;
  padding-left: 0;
  padding-right: 0;
}

/* 操作按钮居中显示优化 */
.expand-cell .expand-button {
  width: 140px;
  min-width: 140px;
  max-width: 140px;
  padding: 8px 14px;
  font-size: 13px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  margin: 0 auto;
}

.expand-cell :deep(.el-icon) {
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 文本溢出处理 - 支持两行显示，超过两行才省略 */
.text-overflow {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: center;
  box-sizing: border-box;
  max-width: 100%;
  position: relative;
  line-height: 1.4;
  max-height: 2.8em;
  /* 2行的高度：1.4 * 2 = 2.8em */
}

/* 技术流程表格中的文本自动换行显示 */
.plan-list .text-overflow {
  display: block;
  text-align: left;
  box-sizing: border-box;
  max-width: 100%;
  position: relative;
  line-height: 1.4;
  word-break: break-word;
  word-wrap: break-word;
  white-space: normal;
  overflow: visible;
}

/* 在计划工作内容弹窗表格内：取消行数限制与省略显示 */
.flow-table :deep(.no-clamp) {
  display: block;
  white-space: normal;
  word-break: break-word;
  overflow: visible;
  -webkit-line-clamp: unset;
  line-clamp: unset;
  text-overflow: unset;
  max-height: none;
}

/* 在左对齐单元格内的文本也左对齐 */
.left-align .text-overflow {
  text-align: left;
}

/* 确保单元格内容不会超出固定宽度 */
.node-cell {
  overflow: hidden;
  box-sizing: border-box;
  position: relative;
  word-wrap: break-word;
  word-break: break-all;
}

/* 强制单元格内容适应固定宽度 */
.node-cell>* {
  max-width: 100%;
  overflow: hidden;
}

/* 灵活的表格布局 - 移除固定布局限制 */

.list-header,
.receive-node-row {
  display: flex;
  width: 100%;
  min-width: 1330px;
}

.text-gray-400 {
  color: #9ca3af;
}



/* 页面包装器样式 */
.page-wrapper {
  width: 100%;
  height: 100%;
}

.box-card {
  border-radius: 12px !important;
}

/* 展开按钮样式 */
.expand-button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 8px 12px;
  border: 2px solid #d1d5db;
  border-radius: 8px;
  background-color: #ffffff;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  font-weight: 500;
  color: #6b7280;
  min-width: 80px;
}

.expand-button:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
  color: #409eff;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.2);
}

.expand-button.expanded {
  border-color: #409eff;
  background-color: #409eff;
  color: #ffffff;
}

.expand-button.expanded:hover {
  background-color: #3b82f6;
  border-color: #3b82f6;
}

.expand-text {
  font-weight: 600;
  letter-spacing: 0.5px;
}

.expand-arrow {
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.3s ease;
}

.expand-arrow.rotated {
  transform: rotate(180deg);
}

.expand-arrow {
  width: 16px;
  height: 16px;
}

/* 展开内容样式 */
.expand-content {
  padding: 20px;
  background: #f8f9fa;
  border: 2px solid #409eff;
  border-radius: 8px;
  margin: 10px 0;
  position: relative;
  animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    max-height: 0;
    padding: 0 20px;
  }

  to {
    opacity: 1;
    max-height: 1000px;
    padding: 20px;
  }
}

.plan-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px 0 16px 0;
  border-bottom: 2px solid #e1e6f0;
}

.plan-header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.plan-icon {
  font-size: 18px;
  color: #409eff;
}

.plan-title {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.plan-header-actions {
  display: flex;
  gap: 8px;
}

/* 计划节点列表样式 */
.plan-list {
  margin-top: 16px;
}



/* 操作按钮组样式 */
.plan-op-buttons {
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.plan-op-buttons :deep(.el-button) {
  padding: 0 6px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .expand-content {
    padding: 15px;
  }

  .plan-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .plan-header-left {
    gap: 8px;
  }

  .list-header {
    display: none;
  }

  .receive-node-row {
    flex-direction: column;
    align-items: stretch;
  }

  .node-cell {
    justify-content: center;
    text-align: center;
    border-right: none;
    border-bottom: 1px solid #f0f0f0;
    padding: 8px 12px;
  }

  .node-cell:last-child {
    border-bottom: none;
  }
}



/* 错误状态样式 */
.is-error :deep(.el-input__wrapper),
.is-error :deep(.el-textarea__inner) {
  border-color: var(--el-color-danger) !important;
  box-shadow: 0 0 0 1px var(--el-color-danger) inset !important;
}

.is-error :deep(.el-input__wrapper:hover) {
  border-color: var(--el-color-danger) !important;
}

/* 技术流程显示样式 */
.tech-flow-display {
  background-color: #f0f9ff;
  padding: 8px 12px;
  border-radius: 6px;
  border-left: 4px solid #409eff;
  font-weight: 500;
  color: #1e40af;
  display: block;
  line-height: 1.4;
  /* 取消内部文本截断，允许内容撑高容器 */
  white-space: normal;
  word-break: break-word;
  overflow: visible;
}

/* 流程编辑表格样式 */
.flow-table {
  width: 100%;
}

.flow-table :deep(.el-table__cell) {
  padding: 8px 0;
}

/* 工作内容/详细工作计划 文本左对齐（覆盖通用 .text-overflow 的居中样式） */
.flow-table :deep(.text-overflow) {
  text-align: left;
  display: block;
  white-space: normal;
  word-break: break-word;
  overflow: visible;
  -webkit-line-clamp: unset;
  line-clamp: unset;
  text-overflow: unset;
  max-height: none;
}

/* 区分编辑态与已保存态的行底色（参照 split 页面） */
.flow-table :deep(.editing-row) {
  background-color: var(--el-color-primary-light-9);
}

.flow-table :deep(.editing-row td) {
  background-color: var(--el-color-primary-light-9) !important;
}

/* 流程编辑表格内的小尺寸组件调整 */
.flow-table :deep(.el-input__wrapper) {
  min-height: 28px;
}

.flow-table :deep(.el-select .el-input__wrapper) {
  min-height: 28px;
}

.flow-table :deep(.el-date-editor.el-input) {
  width: 100%;
}

.flow-table :deep(.el-date-editor .el-input__wrapper) {
  min-height: 28px;
}

.flow-table :deep(.el-textarea__inner) {
  min-height: 60px;
  resize: vertical;
}

/* 流程编辑表格内的数字输入框样式 */
.flow-table :deep(.el-input-number) {
  width: 100%;
}

.flow-table :deep(.el-input-number .el-input__wrapper) {
  min-height: 28px;
}

/* 计算值样式 */
.calculated-value {
  font-weight: 600;
  color: #409eff;
  background-color: #f0f9ff;
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid #e1f5fe;
}

/* 新增流程按钮样式 */
.flow-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px 0 16px 0;
  border-bottom: 2px solid #e1e6f0;
}

.flow-header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.flow-icon {
  font-size: 18px;
  color: #409eff;
}

.flow-title {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.flow-header-actions {
  display: flex;
  gap: 8px;
}

/* 可编辑单元格样式 */
.editable-cell {
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.2s ease;
  min-height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 技术流程列表编辑态行样式 */
.plan-list :deep(.el-table__row) {
  transition: background-color 0.2s ease;
}

.plan-list :deep(.el-table__row.editing-row) {
  background-color: var(--el-color-primary-light-9);
}

.plan-list :deep(.el-table__row.editing-row td) {
  background-color: var(--el-color-primary-light-9) !important;
}


/* 技术流程/备注内容左对齐（覆盖默认center） */
.editable-cell.left {
  justify-content: flex-start;
  text-align: left;
  width: 100%;
}

.editable-cell.left .text-overflow {
  text-align: left;
}

/* 技术流程表格列宽比例控制 */
.plan-list :deep(.el-table) {
  table-layout: fixed;
}

.plan-list :deep(.el-table__body-wrapper) {
  overflow-x: auto;
}

/* 技术流程表格单元格高度控制 - 支持自动换行显示 */
.plan-list :deep(.el-table__cell) {
  padding: 12px 8px;
  min-height: 40px;
  vertical-align: top;
  height: auto;
}

/* 技术流程表格行高控制 - 根据内容自动调整 */
.plan-list :deep(.el-table__row) {
  height: auto;
  min-height: 40px;
}

/* 确保技术流程和备注列按照2:1比例分配 */
.plan-list :deep(.el-table__body td:nth-child(2)) {
  width: 66.67% !important;
  min-width: 66.67% !important;
}

.plan-list :deep(.el-table__body td:nth-child(3)) {
  width: 33.33% !important;
  min-width: 33.33% !important;
}

/* 表头列宽也保持一致 */
.plan-list :deep(.el-table__header th:nth-child(2)) {
  width: 66.67% !important;
  min-width: 66.67% !important;
}

.plan-list :deep(.el-table__header th:nth-child(3)) {
  width: 33.33% !important;
  min-width: 33.33% !important;
}

/* 右下角固定提交审核按钮样式 */
.fixed-submit-button {
  position: fixed;
  right: 30px;
  bottom: 30px;
  z-index: 999;
  transition: all 0.3s ease;
}

.submit-audit-btn {
  min-width: 180px;
  height: 56px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 28px;
  box-shadow: 0 8px 24px rgba(64, 158, 255, 0.3);
  border: none;
  background: linear-gradient(135deg, #409EFF 0%, #66B1FF 100%);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.submit-audit-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 12px 32px rgba(64, 158, 255, 0.4);
  background: linear-gradient(135deg, #337ecc 0%, #5aa1ff 100%);
}

.submit-audit-btn:active {
  transform: translateY(-1px);
  box-shadow: 0 6px 20px rgba(64, 158, 255, 0.35);
}

.submit-audit-btn .el-icon {
  font-size: 18px;
}

.submit-audit-btn span {
  font-size: 16px;
  font-weight: 600;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .fixed-submit-button {
    right: 16px;
    bottom: 16px;
  }

  .submit-audit-btn {
    min-width: 140px;
    height: 48px;
    font-size: 14px;
    border-radius: 24px;
  }

  .submit-audit-btn .el-icon {
    font-size: 16px;
  }

  .submit-audit-btn span {
    font-size: 14px;
  }
}

/* 当页面滚动时的动画效果 */
@keyframes buttonBounce {

  0%,
  20%,
  50%,
  80%,
  100% {
    transform: translateY(0);
  }

  40% {
    transform: translateY(-5px);
  }

  60% {
    transform: translateY(-3px);
  }
}

.fixed-submit-button:hover .submit-audit-btn {
  animation: buttonBounce 0.6s ease;
}

/* 查看模式下的禁用样式 */
.expand-button.disabled {
  opacity: 0.6;
  cursor: not-allowed;
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #909399;
}

.expand-button.disabled:hover {
  transform: none;
  box-shadow: none;
  border-color: #e4e7ed;
  background-color: #f5f7fa;
  color: #909399;
}

/* 禁用状态下的可编辑单元格样式 */
.editable-cell:has(.disabled) {
  cursor: default;
}

/* 查看模式下的按钮禁用样式 */
.el-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>
